package com.heima.behavior.service.impl;

import java.util.Date;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //1,检验参数（检验框架负责）
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "需要登录");
        }
        //2,先查询行为实体数据
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (apBehaviorEntry == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "查询关联行为实体失败");
        }
        //3,如果是点在操作，并且点赞已经存在，提示请勿重复操作
        Short operation = dto.getOperation();
        Query query = Query.query(
                Criteria.where("entryId").is(apBehaviorEntry.getId())
                        .and("articleId").is(dto.getArticleId()));
        if (operation.intValue() == 0) {
            //根据行为实体id + 文章id 查询是否点赞
            ApLikesBehavior likesBehavior = mongoTemplate.findOne(query, ApLikesBehavior.class);
            if (likesBehavior != null) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST, "请勿重复点赞");
            }
            likesBehavior.setEntryId(apBehaviorEntry.getId());
            likesBehavior.setArticleId(dto.getArticleId());
            likesBehavior.setType((short) 0);
            likesBehavior.setOperation((short) 0);
            likesBehavior.setCreatedTime(new Date());
            mongoTemplate.save(likesBehavior);
        } else {
            mongoTemplate.remove(query, ApLikesBehavior.class);
        }
        return ResponseResult.okResult();
    }
}
